<!--
 * @Author: cgl
 * @Date: 2023-04-18 15:12:26
 * @LastEditors: cgl
 * @LastEditTime: 2023-08-28 15:51:33
 * @FilePath: \public-health-emergencies-fed:\radiation-hygiene-fe\src\views\slide\bind.vue
 * @Description:
 *
 * Copyright (c) 2023 by cgl/微盛信息产业有限公司, All Rights Reserved.
-->
<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="100px"
    >
      <el-row>
        <el-col :span="5">
          <el-form-item label="单位名称">
            <m-select
              v-model="queryParams.entrustOrganizationId"
              placeholder="输入文字检索查询"
              style="width: 100%"
              clearable
              filterable
              :lists="organizationList"
              lists_label="organizationName"
              lists_value="entrustOrganizationId"
              lists_key="entrustOrganizationId"
              :total="orgTotal"
              :pageSize="10"
              @handleChange="listeningEvent"
            >
            </m-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="table-wrapper">
      <!-- <div class="operation">
      <el-button class="register" type="primary" size="mini" @click="openDialog()"
        >登记</el-button
      >
    </div> -->
      <el-table
        v-loading="loading"
        :data="dataList"
        @row-dblclick="(row) => openDialog(row, '3')"
      >
        <el-table-column
          label="单位名称"
          align="center"
          prop="entrustOrganizationName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="应收样剂量计"
          align="center"
          prop="shouldBindingCount"
          width="150px"
        />
        <el-table-column
          label="已收样剂量计"
          align="center"
          prop="bindingCount"
          width="150px"
        />
        <!-- <el-table-column label="单号/接样日期" align="center" prop="trackingNumber" width="300px" >
        <template slot-scope="{ row }">
          <div v-for="(item, index) in row.otherDataList" :key="index">
            {{ item.trackingNumber }}({{
              parseTime(item.samplingDate, "{y}-{m}-{d}")
            }})
          </div>
        </template>
      </el-table-column> -->
        <el-table-column
          label="接样日期"
          align="center"
          prop="trackingNumber"
          width="300px"
        >
          <template slot-scope="{ row }">
            <div v-for="(item, index) in row.otherDataList" :key="index">
              {{ parseTime(item.samplingDate, "{y}-{m}-{d}") }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="监测起始时间"
          align="center"
          prop="wearingBeginTime"
          width="150px"
        >
          <template slot-scope="{ row }">
            {{ parseTime(row.wearingBeginTime, "{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column
          label="监测结束时间"
          align="center"
          prop="wearingEndTime"
          width="150px"
        >
          <template slot-scope="{ row }">
            {{ parseTime(row.wearingEndTime, "{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column
          label="要求完成日期"
          align="center"
          prop="requireCompletionDate"
          width="150px"
        >
          <template slot-scope="{ row }">
            {{ parseTime(row.requireCompletionDate, "{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100px">
          <template slot-scope="{ row }">
            <el-button @click.native.prevent="openDialog(row, '2')" type="text">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 绑定弹框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :title="title"
      class="bind-dialog"
      @closed="closeDialog"
      v-dialogDrag="true"
    >
      <div class="container">
        <div class="left-container" v-if="false">
          <div class="left-title">
            <span>应检人员 </span>
            <div class="">
              <span style="size: 16px">单位：</span>
              <el-select
                v-model="queryParams.companyId"
                filterable
                size="mini"
                placeholder="输入文字检索查询"
                style="width: 250px"
                @change="handleChangeCompanyIng"
              >
                <el-option
                  v-for="item in bindingListing"
                  :key="item.taskPersonalDosimeterId"
                  :label="item.label"
                  :value="item.taskPersonalDosimeterId"
                >
                </el-option>
              </el-select>
              <span style="margin-left: 8px"
                >{{ inspectPersonList.length }}（发放：{{
                  useRow.sendNum || 0
                }}）</span
              >
            </div>
          </div>
          <!--  -->
          <!-- <el-form
            v-if="status == '1'"
            :model="queryParams"
            ref="queryParams"
            size="small"
            label-width="100px"
          >
            <el-row type="flex" justify="end">
              <el-col :span="12">
                <el-form-item label="单位">
                  <el-select
                    v-model="queryParams.companyId"
                    filterable
                    placeholder="输入文字检索查询"
                    @change="handleChangeCompanyIng"
                  >
                    <el-option
                      v-for="item in bindingListing"
                      :key="item.taskPersonalDosimeterId"
                      :label="item.label"
                      :value="item.taskPersonalDosimeterId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form> -->
          <el-table
            :data="inspectPersonList"
            style="width: 100%"
            :row-class-name="tableRowClassName"
            @selection-change="handleSelectionChange"
            :style="status != '3' ? 'flex: 0.95' : 'flex: 0.91'"
          >
            <el-table-column
              type="selection"
              width="50px"
              align="center"
              :selectable="selectable"
              v-if="status != '3'"
            ></el-table-column>
            <el-table-column
              prop="entrustOrganizationName"
              label="单位名称"
              align="center"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column
              prop="dosageNumber"
              label="剂量计编号"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="personnelName"
              label="姓名"
              align="center"
              width="80"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.personnelName }}</span>
                <span
                  v-if="scope.row.personnelName && scope.row.dosageType == 1"
                  >(内)</span
                >
                <span
                  v-if="scope.row.personnelName && scope.row.dosageType == 2"
                  >(外)</span
                >
              </template>
            </el-table-column>
            <el-table-column align="center" width="26" class-name="nopadding">
              <template slot-scope="{ row }">
                <i
                  class="el-icon-right"
                  style="color: #2a72ee; cursor: pointer"
                  v-if="status != '3' && !row.exceptional"
                  @click="handleAddRegister(row)"
                ></i>
              </template>
            </el-table-column>
          </el-table>
          <div class="abnormal">
            <el-button
              type="primary"
              :disabled="selected.length == 0"
              v-if="status != '3'"
              @click="handleException"
              >异常报备</el-button
            >
            <el-button
              type="danger"
              :disabled="selected.length == 0"
              v-if="status != '3'"
              @click="handleDelPeople"
              >删除人员</el-button
            >
          </div>
        </div>

        <div class="right-container" style="width: 100%">
          <div class="title-container">
            <div style="display: flex; align-items: center">
              <div class="right-title" :class="status == '3' && 'isView'">
                数据整理
              </div>
              <!-- <el-button type="primary" v-hasPermi="['task:bindBackground:btn']" style="margin-left: 8px" :disabled="!useRow.taskPersonalDosimeterId" @click="handleOpenBind">绑定本底</el-button> -->
              <!-- <el-button type="primary" style="margin-left: 8px" v-if="status == 2" @click="handleOpenDosimeter">添加</el-button> -->
              <!-- <el-button type="primary" @click="handleReset">重 置</el-button> -->
              <!-- <el-date-picker
                v-model="updateWearingTimes"
                type="daterange"
                size="small"
                value-format="yyyy-MM-dd"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleChangeAllWearingTime"
                style="width: 240px;margin-left: 8px;"
              >
              </el-date-picker> -->
            </div>
            <el-row type="flex" align="middle" v-if="false">
              <div class="environment" v-if="status == '1'">
                <span> {{ environment.temperature }}℃</span>
                <span class="humidity">{{ environment.humidity }}%RH</span>
              </div>
              <el-form inline @submit.native.prevent v-if="status != '3'">
                <el-form-item label="检测设备" prop="equipmentId">
                  <el-select
                    v-model="equipmentId"
                    placeholder="输入文字检索查询"
                    size="mini"
                    filterable
                    @change="changeEquipment"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) in equipmentSelect"
                      :label="
                        '(' + item.equipmentNumber + ')' + item.equipmentName
                      "
                      :value="item.equipmentId"
                      :key="index"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <div :style="{ color: isJoin ? 'green' : 'red' }">
                  {{ isJoin ? "设备已连接" : "设备已断开" }}
                </div>
                <!-- <el-form-item label="快递单号" label-width="90px">
                  <el-input
                    v-model="trackingNumber"
                    placeholder="请输入"
                    clearable
                    size="mini"
                    ref="trackingNumber"
                    @keyup.enter.native="submitTracking"
                  >
                  </el-input>
                </el-form-item> -->
              </el-form>
            </el-row>
          </div>

          <el-table
            style="margin-top: 15px"
            :row-class-name="rightTrackingName"
            :data="trackingList"
            height="50%"
          >
            <el-table-column
              prop="dosageNumber"
              label="剂量计编号"
              align="center"
              width="130"
            >
              <template slot-scope="scope">
                <el-input
                  :disabled="
                    scope.row.state != null &&
                    scope.row.state != '0' &&
                    scope.row.state != '-1' &&
                    scope.row.state != '3'
                  "
                  :ref="'dosageRef_' + scope.$index"
                  v-model="scope.row.dosageNumber"
                  clearable
                  size="mini"
                  @change="changedosageNumber($event, scope.row)"
                  @keyup.enter.native="getPersonList(scope.row, scope.$index)"
                  @focus="(e) => handleInputFocus(e, scope.row, scope.$index)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="holeOne" label="读出值1" align="center">
              <template slot-scope="scope">
                <el-input
                  v-if="
                    $auth.hasPermi('task:editValue:feature') &&
                    (scope.row.state == 2 ||
                      ((scope.row.state == 3 ||
                        scope.row.state == 4 ||
                        scope.row.state == 5) &&
                        scope.row.exceptionType != 1))
                  "
                  v-model="scope.row.holeOne"
                  @keyup.enter.native="
                    handleChangeReadValue(scope.row, scope.$index, 'one')
                  "
                ></el-input>

                <el-input
                  v-else
                  :ref="'holeOneRef_' + scope.$index"
                  :disabled="
                    scope.row.state != '0' &&
                    scope.row.state != '1' &&
                    scope.row.state != '-1'
                  "
                  v-model="scope.row.holeOne"
                  clearable
                  size="mini"
                  @keyup.enter.native="
                    hanleSubmitHoleValue(scope.row, scope.$index, 'one')
                  "
                  @focus="(e) => handleInputFocus(e, scope.row, scope.$index)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="holeTwo" label="读出值2" align="center">
              <template slot-scope="scope">
                <el-input
                  v-if="
                    $auth.hasPermi('task:editValue:feature') &&
                    (scope.row.state == 2 ||
                      ((scope.row.state == 3 ||
                        scope.row.state == 4 ||
                        scope.row.state == 5) &&
                        scope.row.exceptionType != 1))
                  "
                  v-model="scope.row.holeTwo"
                  @keyup.enter.native="
                    handleChangeReadValue(scope.row, scope.$index, 'two')
                  "
                ></el-input>
                <el-input
                  v-else
                  :ref="'holeTwoRef_' + scope.$index"
                  :disabled="
                    scope.row.state != '0' &&
                    scope.row.state != '1' &&
                    scope.row.state != '-1'
                  "
                  v-model="scope.row.holeTwo"
                  clearable
                  size="mini"
                  @keyup.enter.native="
                    hanleSubmitHoleValue(scope.row, scope.$index, 'two')
                  "
                  @focus="(e) => handleInputFocus(e, scope.row, scope.$index)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="holeOneDosageValue"
              label="剂量当量1"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="holeTwoDosageValue"
              label="剂量当量2"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="dosageValue"
              label="剂量当量"
            ></el-table-column>
            <!-- <el-table-column
							align="center"
							prop="dosageValue"
							label="名义剂量"
						>
              <template slot-scope="{row}">
                <span v-if="row.notionalDose">{{ row.notionalDose }}</span>
              </template>
            </el-table-column> -->
            <!-- <el-table-column
							align="center"
							prop="trackingNumber"
							label="快递单号"
						></el-table-column> -->
            <el-table-column
              align="center"
              prop="backgroundId"
              :show-overflow-tooltip="true"
              label="本底"
            >
              <template slot-scope="{ row }">
                <el-select
                  v-model="row.backgroundId"
                  placeholder="请选择"
                  style="width: 100%"
                  @change="
                    (val) =>
                      singleBindBackgrounds(row.taskPersonalResultId, val, row)
                  "
                  v-if="row.dosageType != 3"
                >
                  <el-option
                    :label="item.personnelName + item.dosageNumber"
                    :value="item.taskPersonalResultId"
                    v-for="(item, index) in backgroundLists"
                    :key="index"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="personnelName"
              label="姓名"
              width="90px"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.personnelName }}</span>
                <span
                  v-if="scope.row.personnelName && scope.row.dosageType == 1"
                  >(内)</span
                >
                <span
                  v-if="scope.row.personnelName && scope.row.dosageType == 2"
                  >(外)</span
                >
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="监测起止时间"
              align="center"
              width="240"
            >
              <template slot-scope="{ row }">
                <el-date-picker
                  v-model="row.wearingTimes"
                  type="daterange"
                  size="small"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="(val) => handleChangeWearingTime(val, row)"
                  style="width: 100%"
                  :clearable="false"
                >
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="200px"
              align="center"
              v-if="status != '3' && false"
            >
              <template slot-scope="{ row, $index }">
                <el-button
                  v-if="row.dosageType != 3"
                  size="mini"
                  type="text"
                  @click="handleException(row)"
                  >异常报备</el-button
                >
                <el-button
                  v-if="row.dosageType != 3"
                  size="mini"
                  type="text"
                  @click="handleChangeShowReport(row)"
                  >{{ row.showReport == 1 ? "显示" : "隐藏" }}</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  :disabled="row.state == null"
                  :style="`color: ${
                    row.state == null ? '#f32d2d75' : '#f32d2d'
                  }`"
                  @click="deleteItem($index)"
                  >解绑</el-button
                >
                <el-button
                  v-if="!row.exceptional"
                  size="mini"
                  type="text"
                  @click="deletePeople(row, $index)"
                  >删除</el-button
                >
                <!-- <el-button
                  v-if="row.filingFlag == 0"
									size="mini"
									type="text"
									@click="handleRevocationException(row, $index)"
									>撤回异常</el-button
								> -->
              </template>
            </el-table-column>
          </el-table>
          <div class="btns">
            <!-- <div class="filelist">
							查看文件：
							<span class="filelistitem" v-for="(item, index) in fileList" :key="index" @click="viewFile(item)">
								{{ item.name }}
							</span>
						</div> -->
            <el-button
              type="primary"
              icon="el-icon-refresh"
              @click="getOssFile"
              circle
            ></el-button>
            <el-button type="primary" @click="handleGenerate"
              >一 键 生 成</el-button
            >
            <el-button @click="dialogVisible = false">关 闭</el-button>
          </div>
          <el-form
            class="handleform"
            v-if="fileList128.length"
            @submit.native.prevent
            size="small"
            label-width="0"
          >
            <div style="display: flex; justify-content: flex-end">
              <el-form-item class="form-filelist">
                <span class="label">128</span>
                <div
                  style="
                    display: inline-block;
                    border: 1px solid #969696;
                    padding: 0 8px;
                  "
                >
                  <span
                    class="filelistitem"
                    v-for="(item, index) in fileList128"
                    :key="index"
                    @click="viewFile(item)"
                    >{{ item.name }}</span
                  >
                </div>
              </el-form-item>
              <!-- <el-form-item class="form-filelist" style="margin-left: 100px;">
                <span class="label">10264</span>
                <div style="display: inline-block;border: 1px solid #969696;padding: 0 8px;">
                  <span class="filelistitem" v-for="(item, index) in fileList10264" :key="index" @click="viewFile(item)">{{ item.name }}</span>
                </div>
              </el-form-item> -->
            </div>
            <el-form-item class="form-filelist">
              <el-button
                type="primary"
                size="mini"
                @click="handlePrintReports('128')"
                >打印-128</el-button
              >
              <!-- <el-button type="primary" size="mini" @click="handlePrintReports('10264')">打印-10264</el-button> -->
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
    <!-- 不同批次弹窗提示显示 -->
    <el-dialog
      :visible.sync="tipsDialogVisible"
      :close-on-click-modal="false"
      :title="tipsTitle"
      width="60%"
      v-dialogDrag="true"
      append-to-body
    >
      <el-form
        class="saveAddPersonInfo"
        :disabled="true"
        :model="saveAddPersonInfo"
        size="small"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="单位名称">
              <el-input v-model="saveAddPersonInfo.organizationName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系人">
              <el-input
                v-model="saveAddPersonInfo.contactsName"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话">
              <el-input
                v-model="saveAddPersonInfo.contactsMobile"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="单位地址">
              <el-input
                v-model="saveAddPersonInfo.addressDetails"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="saveAddPersonList" style="width: 100%">
        <el-table-column
          prop="entrustOrganizationName"
          label="单位名称"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          prop="dosageNumber"
          label="剂量计编号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="year"
          label="年份"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="batchNum"
          label="批次"
          align="center"
        ></el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="tipsDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!-- 异常报备 -->
    <el-dialog
      :visible.sync="abnormalVisible"
      :close-on-click-modal="false"
      :title="abnormalTitle"
      width="500px"
      v-dialogDrag="true"
      append-to-body
    >
      <el-form
        ref="abnormalRefs"
        class="abnormalVisible"
        :model="abnormalFrom"
        :rules="abnormalRules"
        size="small"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="异常类型" prop="exceptionType">
              <el-select
                v-model="abnormalFrom.exceptionType"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in dict.type.exception_state"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="异常原因" prop="describe">
              <el-autocomplete
                class="inline-input"
                style="width: 100%"
                v-model="abnormalFrom.describe"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                value-key="label"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="名义剂量" prop="addNotionalDoseFlag">
              <el-radio-group v-model="abnormalFrom.addNotionalDoseFlag">
                <el-radio
                  v-for="(item, index) in dict.type.is_or_no"
                  :key="index"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="abnormalFrom.addNotionalDoseFlag == 1">
            <el-form-item label="剂量值" prop="notionalDose">
              <el-input
                v-model="abnormalFrom.notionalDose"
                placeholder="请输入名义剂量"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="handleAbnormalConfim"
          >确 认</el-button
        >
        <el-button @click="abnormalVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加 -->
    <el-dialog
      title="添加剂量计"
      :visible.sync="dosimeterVisible"
      :close-on-click-modal="false"
      width="800px"
      class="dosimeterDialog"
      v-dialogDrag="true"
      :show-close="false"
    >
      <el-form
        :model="dosimeterForm"
        :rules="dosimeterRules"
        ref="dosimeterRefs"
        size="small"
        label-width="120px"
      >
        <el-row :gutter="20">
          <!-- <el-col :span="12">
						<el-form-item label="是否本底" prop="personnelNumber">
							<el-radio-group v-model="radio">
                <el-radio v-for="(item, index) in is_or_no" :key="index" :label="item.value">备选项</el-radio>
              </el-radio-group>
						</el-form-item>
					</el-col> -->
          <el-col :span="12">
            <el-form-item label="人员编号" prop="personnelNumber">
              <el-input
                v-model="dosimeterForm.personnelNumber"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人员姓名" prop="personnelName">
              <el-input
                v-model="dosimeterForm.personnelName"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="人员性别" prop="personnelSex">
              <el-select
                v-model="dosimeterForm.personnelSex"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="(item, index) in dict.type.sys_user_sex"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否穿戴铅衣" prop="wearLeadCoat">
              <el-select
                v-model="dosimeterForm.wearLeadCoat"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="(item, index) in dict.type.is_or_no"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职业类别" prop="occupationalClassification">
              <el-select
                v-model="dosimeterForm.occupationalClassification"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  :label="item.label"
                  :value="item.value"
                  v-for="(item, index) in dict.type.occupational_classification"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="佩戴时间" prop="wearingTimes">
              <el-date-picker
                size="mini"
                v-model="dosimeterForm.wearingTimes"
                class="wearingedit"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="daterange"
                :clearable="false"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="handleDosimeterConfim"
          >确 认</el-button
        >
        <el-button @click="dosimeterVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 环境条件弹框 -->
    <el-dialog
      title="环境条件"
      :visible.sync="environmentVisible"
      :close-on-click-modal="false"
      width="550px"
      class="eviromentDialog"
      v-dialogDrag="true"
      :show-close="false"
    >
      <el-form
        :model="formEnvironment"
        :rules="rulesEnvironment"
        ref="formEnvironment"
        size="small"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="温度(℃)" prop="temperature">
              <el-input
                v-model="formEnvironment.temperature"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="湿度(%RH)" prop="humidity">
              <el-input
                v-model="formEnvironment.humidity"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer">
        <el-button type="primary" @click="submitEnvironment">确 定</el-button>
        <el-button @click="cancelEnvironment">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 绑定本地值 -->
    <bind-background
      ref="bindBackgroundRefs"
      @handleConfirm="handleBindBackground"
    />
  </div>
</template>

<script>
import {
  slidesSampleUpdateState,
  addDosageNumber,
} from "@/api/slides/slideSample";
import { environmentAdd } from "@/api/basicData/environment";
import {
  equipmentListingForDosimeter,
  getEnvironment,
} from "@/api/slides/inspect";
import {
  manuallySlideBinding,
  deviceAbutment,
  getBackgrounds,
  singleBindBackground,
  updateWearingTime,
  updateShowReport,
  getExceptionalInfo,
  personalUpdateRawData,
  personGenerateReportCheck,
  oneClickIssuance,
  personalRemoveResult,
} from "@/api/slides/autoSampleRegister";
import {
  entrustOrganizationListing,
  entrustOrganizationList,
  entrustOrganizationDetail,
} from "@/api/person/entrustOrganization";
import {
  bindingList,
  bindingListing,
  listByDosageNumber,
  getSlideBindingInfo,
  addExceptionalRecord,
  bindingRemove,
} from "@/api/slides/bind";
import {
  removePersonalResult,
  personalDosimeterDetail,
} from "@/api/slides/task";
import MSelect from "@/components/mSelect";
import BindBackground from "./components/bindBackground.vue";
import { isNaturalTimes } from "@/utils/index";
import { listByIds } from "@/api/system/oss";
import { handlePrintReport } from "@/utils/lodop/printFun.js";

export default {
  name: "bind",
  dicts: [
    "is_or_no",
    "exception_type",
    "sys_user_sex",
    "occupational_classification",
    "exception_state",
  ],
  components: {
    MSelect,
    BindBackground,
  },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogVisible: false,
      status: null,
      list: [],
      // 总列表
      dataList: [],
      rulesseason: {
        season: [
          { required: true, message: "批次不能为空", trigger: "change" },
        ],
      },
      // 表单参数
      form: {},
      // 剂量计
      dosimeter: 0,
      loading: false,
      title: null,
      // 快递单号
      trackingNumber: null,
      // 检测设备
      equipmentId: "",
      // 检测设备下拉框
      equipmentSelect: [],
      // 应检人员列表
      inspectPersonList: [],
      // 视图高度
      height: document.documentElement.clientHeight,
      // 单位下拉框
      organizationList: [],
      // 所有单位下拉
      bindingListing: [],
      trackingList: [],
      // 批次
      seasonList: [],
      formseason: {
        season: [],
      },
      seasonData: {},
      seasoninspectPersonList: [],
      row_index: null,
      visibleseason: false,
      selected: [],
      selecteditem: null,

      // 单位查询数据
      organizationQueryData: {
        organizationName: "", //单位名称模糊查询
        pageNum: 1, //页码
        pageSize: 10, //每页展示的条数
      },
      orgTotal: 0,
      saveAddPersonInfo: {},
      saveAddPersonList: [],
      tipsDialogVisible: false,
      tipsTitle: "",
      // 异常
      abnormalTitle: "",
      abnormalVisible: false,
      abnormalFrom: {},
      abnormalRules: {
        describe: [
          {
            required: true,
            message: "异常原因不能为空",
            trigger: ["blur", "change"],
          },
        ],
        addNotionalDoseFlag: [
          {
            required: true,
            message: "名义剂量不能为空",
            trigger: ["blur", "change"],
          },
        ],
        notionalDose: [
          {
            required: true,
            message: "剂量值不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
      // ws连接相关
      ws: null,
      // 当前对应数据
      useRow: {},
      // 环境条件弹框
      formEnvironment: {},
      // 环境信息
      environment: {
        temperature: "", // 温度
        humidity: "", // 湿度
      },
      pingInterval: null,
      environmentVisible: false,
      rulesEnvironment: {
        temperature: [
          { required: true, message: "温度不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (isNaN(value)) {
                callback(new Error("请输入正确的格式"));
              } else {
                callback();
              }
            },
          },
        ],
        humidity: [
          { required: true, message: "湿度不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (isNaN(value)) {
                callback(new Error("请输入正确的格式"));
              } else {
                callback();
              }
            },
          },
        ],
      },
      dosimeterVisible: false,
      dosimeterForm: {},
      dosimeterRules: {
        personnelNumber: [
          {
            required: true,
            message: "人员编号不能为空",
            trigger: ["blur", "change"],
          },
        ],
        personnelName: [
          {
            required: true,
            message: "人员姓名不能为空",
            trigger: ["blur", "change"],
          },
        ],
        personnelSex: [
          {
            required: true,
            message: "人员性别不能为空",
            trigger: ["blur", "change"],
          },
        ],
        wearLeadCoat: [
          {
            required: true,
            message: "是否穿戴铅衣",
            trigger: ["blur", "change"],
          },
        ],
        occupationalClassification: [
          {
            required: true,
            message: "职业类别不能为空",
            trigger: ["blur", "change"],
          },
        ],
        wearingTimes: [
          {
            required: true,
            message: "佩戴时间不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
      backgroundLists: [],
      updateWearingTimes: [], // 批量修改监测时间
      isJoin: false,
      allData: [],

      fileList: [],
      fileRecordList: [],
      fileCmaList: [],
      fileList128: [],
      fileList10264: [],
      handleform: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 获取总列表
    getList() {
      this.loading = true;
      const queryParams = { ...this.queryParams };
      delete bindingList(queryParams)
        .then((response) => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 获取单位下拉框
    listeningEvent(e) {
      let { queryName, pageNum, pageSize, type } = e;
      if (type == "scroll" && pageNum == this.organizationQueryData.pageNum)
        return;
      this.organizationQueryData.organizationName = queryName;
      this.organizationQueryData.pageNum = pageNum;
      this.organizationQueryData.pageSize = pageSize;
      entrustOrganizationList(this.organizationQueryData).then((response) => {
        if (type == "scroll") {
          this.organizationList.push(...response.rows);
        } else {
          this.organizationList = response.rows;
        }
        this.orgTotal = response.total;
      });
    },
    // 获取检测设备下拉框
    getEquipmentListing() {
      equipmentListingForDosimeter().then((response) => {
        this.equipmentSelect = response.data;
        // 如果只有一台设备，默认连接第一台
        if (response.data.length == 1) {
          this.equipmentId = response.data[0].equipmentId;
          this.connectScoket();
        }
      });
    },
    handleInputFocus(e, row, index) {
      console.log(e, row, index);
      this.nowRow = row;
      this.nowRowIndex = index;
    },
    // 切换设备
    changeEquipment(val) {
      console.log(val);
      this.ws && this.closeSocket();
      if (val) {
        this.connectScoket();
      }
    },
    handleOpenBind() {
      this.$refs["bindBackgroundRefs"].openDialog({
        taskDosimeterId: this.useRow.taskPersonalDosimeterId,
      });
    },
    handleChangeReadValue(row, index, type) {
      if (type === "one" && (!row.holeOne || row.holeOne.trim() === "")) {
        this.$modal.msgWarning("读出值1不能为空");
        return false;
      }
      if (type === "two" && (!row.holeTwo || row.holeTwo.trim() === "")) {
        this.$modal.msgWarning("读出值2不能为空");
        return false;
      }
      const data = {
        taskPersonalResultId: row.taskPersonalResultId,
        holeOne: row.holeOne,
        holeTwo: row.holeTwo,
      };
      this.$confirm("是否修改读出值", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          personalUpdateRawData(data)
            .then((res) => {
              this.$modal.msgSuccess("修改成功");
            })
            .finally(() => {
              this.openDialog(this.useRow, "2");
            });
        })
        .catch(() => {});
    },
    // 判断是否可以一键生成
    generateReportCheck() {
      personGenerateReportCheck(this.useRow.taskPersonalDosimeterId).then(
        (res) => {}
      );
    },
    // 一键生成按钮
    handleGenerate() {
      this.$confirm("是否一键生成", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: "一键生成中，请稍后",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          oneClickIssuance(this.useRow.taskPersonalDosimeterId)
            .then((res) => {
              this.$alert(res?.msg || "生成成功", "提示", {
                dangerouslyUseHTMLString: true,
              });
              this.getOssFile();
            })
            .finally((err) => {
              loading.close();
            });
        })
        .catch(() => {});
    },
    // 连接websocket
    async connectScoket() {
      let that = this;
      // let prefixUrl = `ws://${document.location.host}${process.env.VUE_APP_BASE_API}/ws/device/`;
      // this.ws = new WebSocket(prefixUrl + this.equipmentId);
      let { msg: prefixUrl } = await this.getConfigKey("task.ws.path");
      this.ws = new WebSocket(prefixUrl);
      //连接成功建立
      this.ws.onopen = function (event) {
        console.log("建立连接", event);
        this.pingInterval = setInterval(() => {
          if (that.ws.readyState === WebSocket.OPEN) {
            that.ws.send("ping");
          }
        }, 30000); // 每 30 秒发送一次 ping 最好远远小于nginx配置的访问超时事件
      };
      //接收到消息
      this.ws.onmessage = async (event) => {
        console.log("接收到内容：" + event.data);
        const { measureTime, measuredData } =
          JSON.parse(event.data)?.resultValue || {};

        if (measuredData) {
          that.isJoin = true;

          const storageTime = localStorage.getItem("FSWS_lastDetectionTime");
          // 存储的时间与soctet中返回的时间一致，则无需保存
          if (storageTime && storageTime == measureTime) return;
          localStorage.setItem("FSWS_lastDetectionTime", measureTime);
          // 根据当前row输入值
          const { holeOne, holeTwo, taskPersonalResultId } = this.nowRow;
          // 如果数据没有时间
          if (taskPersonalResultId) {
            this.nowRow.detectionTime = measureTime;
            if (!holeOne) {
              this.$set(this.nowRow, "holeOne", measuredData);
              this.hanleSubmitHoleValue(this.nowRow, this.nowRowIndex, "one");
            } else if (!holeTwo) {
              this.$set(this.nowRow, "holeTwo", measuredData);
              this.hanleSubmitHoleValue(this.nowRow, this.nowRowIndex, "two");
            }
          }
        } else {
          that.isJoin = false;
        }
      };
      //连接发生错误
      this.ws.onerror = function (event) {
        console.log("发生错误");
        that.isJoin = false;
      };
      //连接关闭
      this.ws.onclose = function (event) {
        console.log("关闭连接");
        that.isJoin = false;
      };
    },
    // 关闭wocket
    closeSocket() {
      clearInterval(this.pingInterval);
      this.pingInterval = null;
      this.ws.close();
      this.ws = null;
      this.isJoin = false;
    },
    handleAddRegister(row) {
      let newRow = {
        dosageNumber: row.dosageNumber,
        trackingNumber: this.trackingNumber || "",
        // entrustOrganizationId: row.entrustOrganizationId,
        // year: row.year,
        // batchNum: row.batchNum,
      };
      // 绑定本底
      if (!row.backgroundId && row.dosageType != 3) {
        this.$set(
          row,
          "backgroundId",
          this.backgroundLists[0].taskPersonalResultId
        );
        newRow.backgroundId = row.backgroundId;
        this.singleBindBackgrounds(row.taskPersonalResultId, row.backgroundId);
      }

      const newRowIndex = this.trackingList.findIndex((i) => !i.dosageNumber);
      if (newRowIndex < 0) {
        this.trackingList.push(newRow);
      } else {
        this.$set(this.trackingList, newRowIndex, newRow);
        // this.trackingList[newRowIndex] = newRow
      }
      this.getPersonList(
        newRow,
        newRowIndex > 0 ? newRowIndex : this.trackingList.length - 1,
        true
      );
      // 有空则定到空处 没有则新增一行
      this.getFocus();
    },
    // 获取报告
    getOssFile() {
      personalDosimeterDetail(this.useRow.taskPersonalDosimeterId).then(
        async (response) => {
          if (response.data) {
            this.handleform = response.data;
            // const files = [
            //   { name: '记录-128', ossId: response.data.recordOssId },
            //   { name: '记录-10264', ossId: response.data.recordOssId10264 },
            //   { name: '报告-128', ossId: response.data.ossId },
            //   { name: '报告-10264', ossId: response.data.ossId10264 },
            //   { name: '存根-128', ossId: response.data.archivesOssId },
            //   { name: '存根-10264', ossId: response.data.archivesOssId10264 },
            //   { name: '正本-128', ossId: response.data.originalOssId },
            //   { name: '正本-10264', ossId: response.data.originalOssId10264 },
            //   { name: '副本-128', ossId: response.data.copyOssId },
            //   { name: '副本-10264', ossId: response.data.copyOssId10264 },
            // ]
            // this.fileList = await files.reduce(async (pre, cur) => {
            // 	let pres = await pre
            // 	if (cur.ossId) {
            // 		let {data} = await listByIds(cur.ossId)
            // 		pres.push({...data[0], ...cur})
            // 	}
            // 	return await pres
            // }, [])

            const files128 = [
              { name: "原始记录", ossId: response.data.recordOssId },
              { name: "存根", ossId: response.data.archivesOssId },
              { name: "正本", ossId: response.data.originalOssId },
            ];
            this.fileList128 = files128.filter((item) => item.ossId);

            const files10264 = [
              { name: "原始记录", ossId: response.data.recordOssId10264 },
              { name: "存根", ossId: response.data.archivesOssId10264 },
              { name: "正本", ossId: response.data.originalOssId10264 },
            ];
            this.fileList10264 = files10264.filter((item) => item.ossId);
          }
        }
      );
    },
    handlePrintReports(type) {
      if (type == "128") {
        const file = [
          { name: "存根", ossId: this.handleform.archivesOssId },
          { name: "正本", ossId: this.handleform.originalOssId },
        ];
        handlePrintReport(file, "2", true);
      } else if (type == "10264") {
        const file = [
          { name: "存根", ossId: this.handleform.archivesOssId10264 },
          { name: "正本", ossId: this.handleform.originalOssId10264 },
        ];
        handlePrintReport(file, "2", true);
      }
    },
    // 报告预览
    async viewFile(item, isTable, isRecords) {
      if (isTable) {
        /* 已签发列表打开 */
        if (item.ossId) {
          listByIds(item.ossId).then((response) => {
            // isRecords && this.handleIsPrint();
            window.open(response?.data[0]?.url, "PDF", "");
          });
        } else {
          this.$modal.msgWarning("暂无文件");
        }
      } else {
        let { data } = await listByIds(item.ossId);
        if (item.ossId && data) {
          window.open(data[0]?.url, "PDF", "");
        } else {
          this.$modal.msgWarning("暂无文件");
        }
      }
    },
    // 更新状态
    updateState(row, state) {
      slidesSampleUpdateState({
        registrationSlidesSampleId: row.registrationSlidesSampleId,
        state: state,
      }).then((response) => {
        this.getList();
      });
    },
    async getBindingListing() {
      let { code, data } = await bindingListing();
      this.bindingListing = data.reduce((pre, cur) => {
        pre.push({
          ...cur,
          label: `${cur.organizationName}(${cur.year})(${cur.batchNum})`,
        });
        return pre;
      }, []);
      console.log(data);
    },
    handleChangeCompanyIng(val) {
      if (!val) {
        this.inspectPersonList = [];
        this.trackingList = [];
      } else {
        const row = this.bindingListing.find(
          (i) => i.taskPersonalDosimeterId == val
        );
        this.openDialog({
          taskPersonalDosimeterId: val,
          status: "2",
          sendNum: row.sendNum,
        });
      }
    },
    handleBindBackground() {
      this.openDialog(this.useRow, "2");
    },
    rightTrackingName({ row, index }) {
      if (row.exceptional) {
        return "warning-row";
      }
      return "";
    },
    handleRevocationException(row, index) {},
    // 删除剂量计任务数据
    deletePeople(row, index) {
      this.$confirm("是否删除剂量计任务", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          personalRemoveResult(row.taskPersonalResultId)
            .then((res) => {
              this.$modal.msgSuccess("删除成功");
            })
            .catch((err) => {});
        })
        .catch(() => {});
      console.log(row, index);
    },
    // 打开对话框
    async openDialog(row, status) {
      if (row) {
        const response = await getSlideBindingInfo(row.taskPersonalDosimeterId);
        response.data.map((item) => {
          item.wearingTimes = [item.wearingBeginTime, item.wearingEndTime];
        });
        // 左侧
        this.inspectPersonList = response.data.filter((item) => {
          return item.state == "0" || item.state == "-1" || item.state == "3";
        });
        this.inspectPersonList.forEach((item) => {
          item.defaultDosageNumber = item.dosageNumber;
        });
        // 右侧
        this.trackingList = response.data.filter((item) => {
          return item.state != "0" && item.state != "-1" && item.state != "3";
        });
        this.trackingList.forEach((item) => {
          item.defaultDosageNumber = item.dosageNumber;
        });
        if (status == "2") {
          this.status = "2";
          this.title = "修改收样登记";
        }
        if (status == "3") {
          this.status = "3";
          this.title = "查看收样登记";
        }
        this.useRow = row;
        this.getBackgroundsList();

        this.allData = response.data;

        if (this.trackingList?.length == response.data?.length) {
          this.generateReportCheck();
        }
        this.getOssFile();
      } else {
        this.status = "1";
        this.title = "收样登记";
        this.getBindingListing();
      }
      // 自动定位
      this.$nextTick(() => {
        if (this.trackingList.length == 0) {
          this.trackingList.push({});
        }
        this.getFocus();
      });

      // getEnvironment().then((response) => {
      //   if (response.data && response.data.temperature && response.data.humidity) {
      //     this.environment = {
      //       temperature: response.data.temperature,
      //       humidity: response.data.humidity,
      //     };
      //   }else {
      //     this.environmentVisible = true;
      //     this.formEnvironment = {};
      //     this.resetForm("formEnvironment");
      //   }
      // });
      this.getEquipmentListing();
      this.dialogVisible = true;
      // if (!row) {
      // 	this.$nextTick(() => {
      // 		this.$refs[`trackingNumber`].focus();
      // 	})
      // }
    },
    handleReset() {
      this.closeDialog();
      this.openDialog();
    },
    handleChangeAllWearingTime(val) {
      this.$confirm("是否修改所有监测时间", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const arr = [...this.inspectPersonList, ...this.trackingList];
          const data = arr.map((item) => {
            return {
              taskPersonalResultId: item.taskPersonalResultId,
              wearingBeginTime: val[0],
              wearingEndTime: val[1],
            };
          });
          updateWearingTime(data)
            .then((res) => {
              if (res.code == 200) {
                this.openDialog(this.useRow, "2");
                this.$modal.msgSuccess("修改成功");
              }
            })
            .finally(() => {
              this.updateWearingTimes = [];
            });
        })
        .catch(() => {
          this.updateWearingTimes = [];
        });
    },
    // 单个更新佩戴时间
    handleChangeWearingTime(val, row) {
      const arr = [
        {
          taskPersonalResultId: row.taskPersonalResultId,
          wearingBeginTime: val[0],
          wearingEndTime: val[1],
        },
      ];
      updateWearingTime(arr)
        .then((res) => {
          if (res.code == 200) {
            this.openDialog(this.useRow, "2");
            this.$modal.msgSuccess("修改成功");
          }
        })
        .catch((err) => {
          this.$set(row, "wearingTimes", [
            row.wearingBeginTime,
            row.wearingEndTime,
          ]);
        });
    },
    // 修改是否显示在报告中
    handleChangeShowReport(row) {
      updateShowReport(
        row.taskPersonalResultId,
        row.showReport == 0 ? 1 : 0
      ).then((res) => {
        if (res.code == 200) {
          this.openDialog(this.useRow, "2");
          this.$modal.msgSuccess("修改成功");
        }
      });
    },
    // 获取本底
    getBackgroundsList() {
      getBackgrounds({
        taskDosimeterId: this.useRow.taskPersonalDosimeterId,
      }).then((res) => {
        this.backgroundLists = res?.data || [];
      });
    },
    // 切换本底
    singleBindBackgrounds(taskPersonalResultId, backgroundId, row) {
      singleBindBackground({
        taskPersonalResultId,
        backgroundId: backgroundId,
      }).then((res) => {
        if (row && row.state > 0) {
          this.openDialog(this.useRow, "2");
        }
      });
    },
    // 提交剂量计编号
    async getPersonList(row, index, isInitiative = false) {
      if (!row.dosageNumber || row.dosageNumber.trim() === "") {
        this.$modal.msgWarning("剂量计编号不能为空");
        return false;
      }
      let isRepeat = false;

      let shortindex = row.dosageNumber.indexOf("-");
      const arr = this.trackingList.filter((item, ind) => {
        if (row.dosageNumber === item.slidesNumber) {
          /* 剂量计编号与滑片码重复 */
          isRepeat = true;
        }
        if (shortindex != "-1") {
          return (
            ind != index &&
            row.dosageNumber == item.dosageNumber + "-" + item.batchNum
          ); /* 剂量计编号与剂量计编号重复 */
        } else {
          return (
            ind != index && row.dosageNumber == item.dosageNumber
          ); /* 剂量计编号与剂量计编号重复 */
        }
      });
      if (isRepeat) {
        this.$modal.msgWarning(
          `剂量计编号：${row.dosageNumber}与剂量元件码重复`
        );
        this.$set(row, "dosageNumber", "");
        this.$refs[`dosageRef_${index}`].focus();
        return;
      }
      if (arr.length >= 1) {
        if (shortindex != "-1") {
          let dosageleft = row.dosageNumber.slice(0, shortindex);
          this.$modal.msgWarning(`剂量计编号：${dosageleft}已存在`);
        } else {
          this.$modal.msgWarning(`剂量计编号：${row.dosageNumber}已存在`);
        }
        this.$set(row, "dosageNumber", "");
        this.$refs[`dosageRef_${index}`].focus();
        return;
      }
      if (row.dosageNumber.trim() !== "") {
        this.listPersonList(row, index, isInitiative);
      }
    },
    // 请求人员数据
    async listPersonList(row, row_index, isInitiative) {
      let shortindex = row.dosageNumber.indexOf("-");
      let dosageleft = "";
      let dosageright = "";
      if (shortindex != "-1" && !isInitiative) {
        const noget = row.dosageNumber.substr(shortindex, 2);
        dosageleft = row.dosageNumber.replace(noget, "");
        console.log(dosageleft);
        dosageright = row.dosageNumber.slice(shortindex + 1);
      } else {
        dosageleft = row.dosageNumber;
        dosageright = "";
      }

      this.$set(row, "dosageNumber", dosageleft);
      this.$set(row, "dosageright", dosageright);

      const index = this.inspectPersonList.findIndex(
        (item) => item.dosageNumber === dosageleft
      );
      if (index > -1) {
        /* 左侧有 */
        const obj = this.inspectPersonList[index];
        for (const key in obj) {
          this.$set(row, key, obj[key]);
        }
        this.inspectPersonList.splice(index, 1);
        this.getFocus();

        // 绑定本底
        if (!row.backgroundId) {
          this.$nextTick(async () => {
            await this.getBackgroundsList();
            this.$set(
              row,
              "backgroundId",
              this.backgroundLists[0].taskPersonalResultId
            );
            let findObj = [
              ...this.trackingList,
              ...this.inspectPersonList,
            ].find((i) => i.dosageNumber == row.dosageNumber);
            if (findObj.dosageType != 3) {
              this.singleBindBackgrounds(
                findObj.taskPersonalResultId,
                row.backgroundId
              );
            }
          });
        }
      } else {
        /* 左侧没有 */
        if (row.dosageNumber == row.defaultDosageNumber) {
          /* 键入相同值 不请求 */
          return;
        }
        // let querydosage = row.dosageright ? (row.dosageNumber + "-" + row.dosageright) : row.dosageNumber;
        let querydosage = row.dosageNumber;
        listByDosageNumber(querydosage)
          .then(async (response) => {
            if (response.data.length === 0) {
              row.dosageNumber = "";
              this.$modal.msgWarning("没有查到应检人员,请重新输入");
              this.$refs["dosageRef_" + row_index].focus();
              return;
            } else {
              this.useRow = {
                taskPersonalDosimeterId:
                  response.data[0].taskPersonalDosimeterId,
              };
              response.data.forEach((item) => {
                item.defaultDosageNumber = item.dosageNumber;
                item.wearingTimes = [
                  item.wearingBeginTime,
                  item.wearingEndTime,
                ];
              });
              this.row_index = row_index;
              // 判断是否为同一单位， 同一年份，同一批次
              const isBoolean = await this.judgeTips(row);
              if (isBoolean >= 0) {
                let { data } = await entrustOrganizationDetail(
                  response.data[0].entrustOrganizationId
                );
                this.saveAddPersonInfo = data;
                // 单位  联系人 电话  地址
                // this.tipsTitle = `${data.organizationName} ${data.dosageContactsName} ${data.dosageContactsMobile} ${data.addressDetails}`
                this.tipsTitle = `查看详情`;
                this.saveAddPersonList = [...response.data];
                this.$set(this.trackingList[row_index], "dosageNumber", "");
                this.$refs["dosageRef_" + row_index].focus();
              } else {
                await this.pushdata(response.data);

                // 绑定本底
                if (!row.backgroundId) {
                  this.$nextTick(async () => {
                    await this.getBackgroundsList();
                    this.$set(
                      row,
                      "backgroundId",
                      this.backgroundLists[0].taskPersonalResultId
                    );
                    let findObj = [
                      ...this.trackingList,
                      ...this.inspectPersonList,
                    ].find((i) => i.dosageNumber == row.dosageNumber);
                    if (findObj.dosageType != 3) {
                      this.singleBindBackgrounds(
                        findObj.taskPersonalResultId,
                        row.backgroundId
                      );
                    }
                  });
                }
              }
            }
          })
          .catch((response) => {
            row.dosageNumber = "";
            this.$refs["dosageRef_" + row_index].focus();
          });
      }
    },
    // 检测本检测周期的个人剂量计提示
    async judgeTips(row) {
      const isTips = [
        ...this.trackingList,
        ...this.inspectPersonList,
      ].findIndex((i) => {
        if (!i.dosageNumber) {
          // 判断是空 则默认为假  不展示提示
          return false;
        }
        return (
          i.entrustOrganizationId != row.entrustOrganizationId ||
          i.year != row.year ||
          i.batchNum != row.batchNum
        );
      });
      if (isTips >= 0) {
        this.tipsDialogVisible = true;
        this.$modal.msgWarning(`不是本检测周期的个人剂量计`);
      }
      return isTips;
    },
    // 将获取的数据推入左右两侧
    async pushdata(list) {
      // 从获取的列表中寻找当前键入人员
      let row = this.trackingList[this.row_index];
      const obj = list.find((item) => {
        return item.dosageNumber === row.dosageNumber;
      });
      if (obj) {
        if (obj.state == "3") {
          /* state为3或exceptional为true 移入左边 */
          this.inspectPersonList.push(obj);
          for (const key in row) {
            this.$set(row, key, null);
          }
        } else {
          for (const key in obj) {
            this.$set(row, key, obj[key]);
          }
          // 已经出结果的用本身的快递单号 否则用新输入的
          if (!obj.state || (obj.state == "0" && obj.state == "-1")) {
            this.$set(row, "trackingNumber", this.trackingNumber);
          }
        }
      }

      // 过滤
      this.$nextTick(() => {
        // 推入左侧
        let lList = list.filter((item) => {
          return (
            item.dosageNumber != row.dosageNumber &&
            (item.state == "0" || item.state == "-1" || item.state == "3")
          );
        });
        let lListFilt = lList.filter((item) => {
          return !this.inspectPersonList.find(
            (it) =>
              item.dosageNumber == it.dosageNumber &&
              item.batchNum === it.batchNum
          );
        });

        lListFilt.forEach((item) => {
          item.defaultDosageNumber = item.dosageNumber;
        });

        // 首次调用接口可以插入左侧   后续调用均不插入且保存数据方便dialog弹窗展示
        if (this.inspectPersonList.length == 0) {
          this.inspectPersonList.push(...lListFilt);
        } else {
          this.saveAddPersonList = [...list];
          console.log(this.saveAddPersonList);
        }

        // 推入右侧
        let rList = list.filter((item) => {
          return (
            item.dosageNumber != row.dosageNumber &&
            item.state != "0" &&
            item.state != "-1" &&
            item.state != "3"
          );
        });
        let rListFilt = rList.filter((item) => {
          return !this.trackingList.find((it) => {
            return (
              item.dosageNumber == it.dosageNumber &&
              item.batchNum == it.batchNum
            );
          });
        });
        rListFilt.forEach((item) => {
          item.defaultDosageNumber = item.dosageNumber;
        });
        if (this.trackingList.length == 1) {
          this.trackingList.unshift(...rListFilt);
          this.getFocus();
        }
      });
    },
    // 键入不同值 清空信息 （正确值会清空并重赋信息）
    changedosageNumber(val, row) {
      if (row.personnelName && val != row.defaultDosageNumber) {
        /* 键入不同值 还原  */
        let obj = { ...row };
        obj.dosageNumber = row.defaultDosageNumber;
        this.inspectPersonList.push(obj);
        console.log("键入不同值", obj);
        this.$set(row, "entrustOrganizationId", null);
        this.$set(row, "entrustOrganizationName", null);
        this.$set(row, "personnelId", null);
        this.$set(row, "personnelName", null);
        this.$set(row, "taskPersonalResultId", null);
        this.$set(row, "wearingBeginTime", null);
        this.$set(row, "wearingEndTime", null);
        this.$set(row, "slidesNumber", null);
        this.$set(row, "batchNum", null);
        this.$set(row, "dosageright", null);
        this.$set(row, "exceptional", null);
      }
    },
    // 绑定
    hanleSubmitHoleValue(row, index, type) {
      if (typeof index === "number" && !isNaN(index)) {
        if (!row.dosageNumber || row.dosageNumber.trim() === "") {
          this.$modal.msgWarning("请先输入剂量计编号");
          this.$set(row, "slidesNumber", "");
          this.$refs[`dosageRef_${index}`].focus();
          return false;
        }
        if (type === "one" && (!row.holeOne || row.holeOne.trim() === "")) {
          this.$modal.msgWarning("读出值1不能为空");
          return false;
        }

        if (type === "two" && (!row.holeTwo || row.holeTwo.trim() === "")) {
          this.$modal.msgWarning("读出值2不能为空");
          return false;
        }
        let data = {
          taskPersonalResultId: row.taskPersonalResultId,
          equipmentId: this.equipmentId,
          trackingNumber: row.trackingNumber,
          detectionTime: row?.detectionTime,
        };
        type == "one"
          ? (data.readoutValue1 = row.holeOne)
          : (data.readoutValue2 = row.holeTwo);
        manuallySlideBinding(data).then((res) => {
          // const data = res.data
          // data.map(item => {
          //   const index = this.trackingList.findIndex(i => i.dosageNumber === item.dosageNumber)
          //   if (index > -1) {
          //     this.$set(this.trackingList[index], 'holeOneDosageValue', item.holeOneDosageValue)
          //     this.$set(this.trackingList[index], 'holeTwoDosageValue', item.holeTwoDosageValue)
          //     this.$set(this.trackingList[index], 'dosageValue', item.dosageValue)

          //     if (type == 'two' && item.holeOne && item.holeTwo) {
          //       this.$set(this.trackingList[index], 'state', 4)
          //     }
          //   }
          // })
          // 判断为孔二提交并数据全部提交  弹出是否一键生成
          if (
            type == "two" &&
            this.trackingList.length == this.allData.length
          ) {
            this.handleGenerate();
          }
          this.openDialog(this.useRow, "2");
          setTimeout(() => {
            this.getFocus();
          }, 500);
        });
      }
    },
    // 提交快递单号
    submitTracking() {
      // if (!this.trackingNumber || this.trackingNumber.trim() === "") {
      // 	return this.$modal.msgWarning("快递单号不能为空");
      // }
      if (this.trackingList.length == 0) {
        this.trackingList.push({
          trackingNumber: this.trackingNumber || "",
        });
      }
      // 有空则定到空处 没有则新增一行
      this.getFocus();
    },
    // 光标定位(从index行开始向下搜寻为空且没有禁用的格子，找到则聚焦，没有则搜寻下一行，到最后一行还没找到，则新增一行)
    getFocus(index = 0) {
      this.$nextTick(() => {
        const value = this.$refs[`dosageRef_${index}`]?.value;
        const holeOneValue = this.$refs[`holeOneRef_${index}`]?.value;
        const holeTwoValue = this.$refs[`holeTwoRef_${index}`]?.value;
        if (
          (!value || value.trim() === "") &&
          !this.$refs[`dosageRef_${index}`].disabled
        ) {
          this.$refs[`dosageRef_${index}`].focus();
          this.trackingList[index].trackingNumber = this.trackingNumber;
          return false;
        } else if (
          (!holeOneValue || holeOneValue.trim() === "") &&
          !this.$refs[`holeOneRef_${index}`].disabled
        ) {
          this.$refs[`holeOneRef_${index}`].focus();
          this.trackingList[index].trackingNumber = this.trackingNumber;
          return false;
        } else if (
          (!holeTwoValue || holeTwoValue.trim() === "") &&
          !this.$refs[`holeTwoRef_${index}`].disabled
        ) {
          this.$refs[`holeTwoRef_${index}`].focus();
          this.trackingList[index].trackingNumber = this.trackingNumber;
          return false;
        }
        // 当index等于绑定登记列表的下标值时 则新增一条
        if (index === this.trackingList.length - 1) {
          this.trackingList.push({
            trackingNumber: this.trackingNumber,
          });
        }
        this.getFocus(index + 1);
      });
    },
    // 解绑
    deleteItem(index) {
      const state = this.trackingList[index].state;
      if (state == -1 || state == 0) {
        this.trackingList[index].state = 0;
        this.trackingList[index].slidesNumber = null;
        this.inspectPersonList.push(this.trackingList[index]);
        this.trackingList.splice(index, 1);
        this.$modal.msgSuccess("解绑成功");
        this.getFocus(index);
        return;
      }
      this.$modal.confirm(`确定解绑该剂量计吗？`).then(() => {
        bindingRemove(this.trackingList[index].taskPersonalResultId).then(
          (response) => {
            this.trackingList[index].state = 0;
            this.trackingList[index].slidesNumber = null;
            this.inspectPersonList.push(this.trackingList[index]);
            this.trackingList.splice(index, 1);
            this.$modal.msgSuccess("解绑成功");
            this.getFocus(index);
          }
        );
      });
    },
    // 更改勾选
    handleSelectionChange(selection) {
      this.selected = selection;
    },
    // 异常报备
    async handleException(row) {
      let ids = this.selected.map((item) => {
        if (item.taskPersonalResultId) {
          return item.taskPersonalResultId;
        }
      });
      this.abnormalTitle = "确定异常报备吗？";
      this.abnormalFrom = {
        taskPersonalResultId: ids,
        exceptionType: "1",
        addNotionalDoseFlag: "1",
      };

      if (row?.taskPersonalResultId) {
        let { data } = await getExceptionalInfo(row.taskPersonalResultId);
        this.abnormalFrom = {
          ...this.abnormalFrom,
          ...data,
          taskPersonalResultId: [row.taskPersonalResultId],
        };
      }
      this.abnormalVisible = true;
    },
    handleDelPeople() {
      let ids = this.selected.map((item) => {
        if (item.taskPersonalResultId) {
          return item.taskPersonalResultId;
        }
      });
      this.$confirm("是否删除应检人员", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removePersonalResult({
            taskPersonalDosimeterId: this.useRow.taskPersonalDosimeterId,
            taskPersonalResultIds: ids,
          }).then((res) => {
            ids.forEach((item) => {
              let index = this.inspectPersonList.findIndex(
                (i) => i.taskPersonalResultId == item
              );
              index > -1 && this.inspectPersonList.splice(index, 1);
            });
            this.$modal.msgSuccess("删除成功");
          });
        })
        .catch(() => {});
    },
    handleAbnormalConfim() {
      this.$refs["abnormalRefs"].validate((valid) => {
        if (!valid) return;

        addExceptionalRecord(this.abnormalFrom).then((response) => {
          this.$modal.msgSuccess("报备成功");
          this.selected.forEach((item) => {
            item.exceptional = true;
          });
          this.selected = [];
          this.openDialog(this.useRow, "2");
          this.abnormalVisible = false;
        });
      });
    },
    querySearch(queryString, cb) {
      let restaurants = this.dict.type.exception_type;
      let results = queryString
        ? restaurants.filter((i) => i.label.indexOf(queryString) > -1)
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    // 提交温度
    submitEnvironment() {
      this.$refs["formEnvironment"].validate((valid) => {
        if (!valid) return;
        environmentAdd(this.formEnvironment).then((response) => {
          this.$modal.msgSuccess("保存成功");
          this.environmentVisible = false;
          this.openDialog();
        });
      });
    },
    // 添加收样登记的剂量计
    handleOpenDosimeter() {
      this.dosimeterVisible = true;
      this.dosimeterForm = {};
    },
    handleDosimeterConfim() {
      this.$refs["dosimeterRefs"].validate((valid) => {
        if (!valid) return;
        this.dosimeterForm.taskPersonalDosimeterId =
          this.useRow.taskPersonalDosimeterId;
        this.dosimeterForm.wearingBeginTime =
          this.dosimeterForm.wearingTimes[0] || null;
        this.dosimeterForm.wearingEndTime =
          this.dosimeterForm.wearingTimes[1] || null;
        addDosageNumber(this.dosimeterForm).then((response) => {
          this.$modal.msgSuccess("添加成功");
          this.dosimeterVisible = false;
          this.openDialog(this.useRow, "2");
        });
      });
    },
    // 关闭环境弹窗
    cancelEnvironment() {
      this.environmentVisible = false;
      this.dialogVisible = false;
    },
    // 关闭弹框
    closeDialog() {
      this.trackingNumber = null;
      this.dosimeter = 0;
      this.useRow = {};
      this.trackingList = [];
      this.inspectPersonList = [];
      this.dialogVisible = false;
      this.queryParams.companyId = "";
      this.closeSocket();
      this.getList();
    },
    // 列表标红
    tableRowClassName({ row, rowIndex }) {
      if (row.exceptional) {
        return "warning-row";
      }
      return "";
    },
    // 已报备的不允许勾选
    selectable(row, rowIndex) {
      if (row.exceptional) {
        return false;
      } else {
        return true;
      }
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryParams");
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
}

::v-deep.el-table {
  .nopadding {
    .cell {
      padding: 0;
    }
  }
}
.bind-dialog {
  ::v-deep.el-dialog {
    background: transparent;
    .el-dialog__header {
      display: none;
    }
    .el-dialog__body {
      padding: 0 0;
      max-height: unset !important;
      .el-table--medium .el-table__cell {
        padding: 4px 0;
      }
    }
  }
}
.container {
  display: flex;

  .left-container {
    border-radius: 10px;
    overflow: auto;
    width: 30%;
    margin-right: 10px;
    background: #fff;
    padding: 10px 15px;
    display: flex;
    flex-direction: column;
    .left-title {
      height: 40px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      > span {
        &:first-child {
          position: relative;
          color: #252d57;
          font-weight: bold;
          padding-left: 15px;
          font-size: 18px;
          &::before {
            content: "";
            width: 5px;
            height: 100%;
            background-color: #2a72ee;
            border-radius: 5px;
            position: absolute;
            left: 0;
            bottom: 0;
          }
        }
      }
    }
    .el-table {
      overflow: auto;
    }
    .abnormal {
      width: fit-content;
      margin: auto auto 0 auto;
    }
  }
  .right-container {
    position: relative;
    background: #fff;
    border-radius: 10px;
    overflow: auto;
    width: 70%;
    text-align: center;
    padding: 10px 15px;
    display: flex;
    flex-direction: column;
    .title-container {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .right-title {
        position: relative;
        color: #252d57;
        font-weight: bold;
        padding-left: 15px;
        font-size: 18px;
        &::before {
          content: "";
          width: 5px;
          height: 100%;
          background-color: #2a72ee;
          border-radius: 5px;
          position: absolute;
          left: 0;
          bottom: 0;
        }
      }

      .environment {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 0 16px;
        font-size: 16px;
        font-weight: bolder;
        .humidity {
          transform: translateY(1px);
          margin-left: 20px;
        }
      }
      ::v-deep.el-form-item {
        margin-bottom: 3px;
      }
    }
    .el-table {
      overflow: auto;
      flex: 0.92;
    }
    .closedialog {
      width: fit-content;
      margin: auto auto 0 auto;
    }
    .btns {
      display: flex;
      justify-content: center;
      align-items: center;
      margin: auto auto 10px auto;
      position: relative;
      z-index: 9;
      .joinTips {
        position: absolute;
        left: 16px;
        bottom: 3%;
        transform: translateY(-50%);
      }
      .filelist {
        position: absolute;
        left: 10%;
        bottom: 5%;
        transform: translateY(-50%);
        .filelistitem {
          color: #2a72ee;
          cursor: pointer;
          &:hover {
            color: #2a72ee;
            text-decoration: underline;
          }
        }
      }
    }
  }
  .row-hei {
    width: 100%;
    height: 90%;
  }
}

.handleform {
  position: absolute;
  width: 100%;
  right: 15px;
  bottom: 0px;
  text-align: right;
  .form-filelist {
    .label {
      margin-right: 8px;
      font-weight: bold;
      font-size: 18px;
    }
    .filelistitem {
      color: #2a72ee;
      cursor: pointer;
      margin-right: 16px;
      &:hover {
        color: #2a72ee;
        text-decoration: underline;
      }
      &:last-of-type {
        margin-right: 0;
      }
    }
  }
}

.operation {
  margin-bottom: 15px;
  .register {
    padding-inline: 30px;
  }
}
.uploadbutton {
  padding-inline: 20px;
}
.myupload {
  margin-bottom: 20px;
}
.result {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
  .calc {
    width: min-content;
    margin-left: 20px;
    .el-button {
      margin: 0;
      &:nth-of-type(1) {
        margin-bottom: 10px;
      }
    }
  }
}
.nametitle {
  text-align: center;
  margin-bottom: 10px;
  font-weight: bolder;
  &::before {
    content: "* ";
    color: red;
  }
}
::v-deep .el-table .warning-row {
  color: red;
}
.searchcontainer {
  display: flex;
  justify-content: space-between;
  align-items: center;

  margin-top: -10px;
}
.viewform {
  justify-content: flex-end;
}
.seasondialog .el-dialog__body .el-form {
  width: fit-content;
  margin: 0 auto;
}
::v-deep .bind-dialog.el-dialog__wrapper {
  top: 10px;
  right: 10px;
  bottom: 10px;
  left: 10px;
  .el-dialog {
    width: 100%;
    height: 100%;
    margin-top: 0 !important;
    max-height: 100%;
    .el-dialog__body {
      height: 100%;
      .container {
        height: 100%;
      }
    }
  }
}
.seasonitem {
  display: flex;
  align-items: center;
  width: fit-content;
  margin-left: 130px;
  margin-bottom: 10px;
  .el-button {
    margin-left: 20px;
  }
}
.seasondialog {
  ::v-deep .el-dialog__body {
    padding-bottom: 10px;
  }
}
.isView {
  margin-bottom: 7px;
  margin-top: 10px;
}
</style>
